#include "hashpipe_error.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

void log_timestamp(char* time_stamp)
{
    time_t now;
    time(&now);
    ctime_r(&now, time_stamp);
    time_stamp[strlen(time_stamp) - 1] = '\0';
}

/* For now just put it all to stderr.
 * Maybe do something clever like a stack in the future?
 */
void hashpipe_error(const char* name, const char* msg, ...)
{
    char timestamp[256];
    log_timestamp(timestamp);
    fprintf(stderr, "%s : ", timestamp);
    fprintf(stderr, "Error (%s)", name);
    if (msg) {
        va_list ap;
        va_start(ap, msg);
        fprintf(stderr, ": ");
        vfprintf(stderr, msg, ap);
        va_end(ap);
    }
    if (errno) {
        fprintf(stderr, " [%s]", strerror(errno));
    }
    fprintf(stderr, "\n");
    fflush(stderr);
}

void hashpipe_warn(const char* name, const char* msg, ...)
{
    char timestamp[256];
    log_timestamp(timestamp);
    fprintf(stderr, "%s : ", timestamp);
    fprintf(stderr, "Warning (%s)", name);
    if (msg) {
        va_list ap;
        va_start(ap, msg);
        fprintf(stderr, ": ");
        vfprintf(stderr, msg, ap);
        va_end(ap);
    }
    fprintf(stderr, "\n");
    fflush(stderr);
}

void hashpipe_info(const char* name, const char* msg, ...)
{
    char timestamp[256];
    log_timestamp(timestamp);
    fprintf(stderr, "%s : ", timestamp);
    fprintf(stderr, "Info (%s)", name);
    if (msg) {
        va_list ap;
        va_start(ap, msg);
        fprintf(stderr, ": ");
        vfprintf(stderr, msg, ap);
        va_end(ap);
    }
    fprintf(stderr, "\n");
    fflush(stderr);
}
